﻿// Copyright 2012, mark.yang.d All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Author: mark.yang.d@gmail.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Data;
using System.Data.Common;

namespace MicroOrm
{
    public class Procedure : DynamicObject
    {
        private string _procedureName;
        private Database _database;

        public Procedure(string procedureName, Database database)
        {
            _procedureName = procedureName;
            _database = database;
        }

        public dynamic Execute(ExecuteMode mode, params object[] parameters)
        {
            object result = null;

            IList<Parameter> ps = new List<Parameter>();
            ProcedureSchema procedureSchema = _database.SchemaProvider.GetProcedureSchema(_procedureName);
            if (procedureSchema.Parameters.Count() > 0)
            {
                for (int i = 0; i < parameters.Length; i++)
                {
                    if (parameters[i] is Parameter)
                        ps.Add((Parameter)parameters[i]);
                    else
                    {
                        if (procedureSchema.Parameters.Any(n => n.Position == i + 1))
                        {
                            ParameterSchema p = procedureSchema.Parameters.First(n => n.Position == i + 1);
                            ps.Add(new Parameter(p.ParameterName, parameters[i]));
                        }
                        else
                            throw new Exception(string.Format("Procedure {0} has too many arguments specified.", _procedureName));
                    }
                }
            }

            IList<DbParameter> outputParameters = new List<DbParameter>();
            ICommandProvider commandProvider = CommandProviderFactory.GetCommandProvider(_database, this);
            IDbCommand command = commandProvider.GetProcedureCommand(_procedureName, outputParameters, ps.ToArray());

            if (_database.Transaction != null)
                command.Transaction = _database.Transaction;

            _database.GetConnection().OpenIfClosed();

            if (mode == ExecuteMode.NonQuery)
                result = command.ExecuteNonQuery();
            else if (mode == ExecuteMode.Scalar)
                result = command.ExecuteScalar();
            else
            {
                IDataReader reader = command.ExecuteReader();
                IEnumerable<Dictionary<string, object>> records = Extensions.GetRecords(reader);

                if (!reader.IsClosed)
                    reader.Close();

                result = new Result(_database, records);
            }

            if (_database.Scope == null)
                _database.GetConnection().CloseIfOpened();

            foreach (DbParameter dp in outputParameters)
            {
                string parameterName = dp.ParameterName.Substring(1);
                if (ps.Any(n => string.Equals(n.ParameterName, parameterName, StringComparison.OrdinalIgnoreCase)))
                {
                    Parameter p = ps.First(n => string.Equals(n.ParameterName, parameterName, StringComparison.OrdinalIgnoreCase));
                    p.Value = dp.Value;
                }
            }

            return result;
        }
    }

    public enum ExecuteMode
    {
        NonQuery = 1,
        Scalar = 2,
        ResultSet = 3
    }
}
